home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / nihcl-30.lha / nihcl-3.0 / ex / ex5-5.c < prev    next >
C/C++ Source or Header  |  1990-05-15  |  1KB  |  43 lines

  1. // ex5-5 -- Opening a stream for a file
  2.  
  3. // $Header: /afs/alw.nih.gov/unix/sun4_40c/usr/local/src/nihcl-3.0/share/ex/RCS/ex5-5.c,v 3.0 90/05/15 22:45:27 kgorlen Rel $
  4.  
  5. #include <fcntl.h>
  6. #include <osfcn.h>
  7. #include <libc.h>
  8. #include <fstream.h>
  9.  
  10. const char* fname = "ex5-5.1.out";
  11. const char* fdname = "ex5-5.2.out";
  12.  
  13. main() 
  14. {
  15.     // open ofstream attached to
  16.     // file on default directory
  17.     ofstream ostrm(fname,ios::out|ios::nocreate);
  18.  
  19.     //  since ios::nocreate is set
  20.     // construction fails when file doesn't already exist
  21.     if ( !ostrm.good() ) {
  22.         perror("ofstream");
  23.         exit(1);
  24.         }
  25.     ostrm << "output to ofstream attached to named file" 
  26.           << endl;
  27.  
  28.     // old-style open to get open file descriptor
  29.     int fd;
  30.     if ( (fd=open(fdname,O_WRONLY,0644)) <0 ) {
  31.         perror("open");
  32.         exit(1);
  33.         }
  34.  
  35.     // close ofstream and 
  36.     // reattach to open file descriptor
  37.     ostrm.close();
  38.     ostrm.attach(fd);
  39.     ostrm << "output to ofstream reattached"
  40.           << " to open file descriptor"
  41.           << endl;
  42. }
  43.